package cn.chiship.framework.third.biz.wxpub.service.impl;

import cn.chiship.framework.common.service.GlobalCacheService;
import cn.chiship.framework.docs.biz.service.FileResourcesService;
import cn.chiship.framework.third.biz.wxpub.pojo.dto.BasicMaterialsDto;
import cn.chiship.framework.third.core.common.MaterialsTypeEnum;
import cn.chiship.framework.third.core.common.ThirdUtil;
import cn.chiship.framework.third.core.enums.ThirdContentStatusEnum;
import cn.chiship.sdk.cache.vo.CacheUserVO;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.util.ObjectUtil;
import cn.chiship.sdk.core.util.PrintUtil;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.third.biz.wxpub.mapper.ThirdWechatArticleMapper;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatArticle;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatArticleExample;
import cn.chiship.framework.third.biz.wxpub.service.ThirdWechatArticleService;
import cn.chiship.sdk.framework.pojo.vo.UploadVo;
import cn.chiship.sdk.third.core.wx.enums.WxPubMaterialTypeEnum;
import cn.chiship.sdk.third.service.WxPubService;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文章素材业务接口实现层 2022/7/13
 *
 * @author lijian
 */
@Service
public class ThirdWechatArticleServiceImpl extends BaseServiceImpl<ThirdWechatArticle, ThirdWechatArticleExample>
        implements ThirdWechatArticleService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThirdWechatArticleServiceImpl.class);

    private static final String KEY_URL = "url";

    private static final String KEY_MEDIA_ID = "media_id";

    @Resource
    ThirdWechatArticleMapper thirdWechatArticleMapper;

    @Resource
    private GlobalCacheService globalCacheService;

    @Resource
    private WxPubService wxPubService;

    @Resource
    FileResourcesService fileResourcesService;

    void wxPubServiceConfig() {
        wxPubService.config(globalCacheService.getWeiXinConfigByAppId(ThirdUtil.getAppId())).token();
    }

    @Override
    public BaseResult saveBasic(BasicMaterialsDto basicMaterialsDto, MultipartFile file, CacheUserVO cacheUserVO) {

        ThirdWechatArticle thirdWechatArticle = new ThirdWechatArticle();
        BeanUtils.copyProperties(basicMaterialsDto, thirdWechatArticle);
        thirdWechatArticle.setSummary(basicMaterialsDto.getContent());
        thirdWechatArticle.setAuthor(cacheUserVO.getRealName());
        if (Arrays
                .asList(MaterialsTypeEnum.BASIC_MATERIALS_TYPE_IMAGE.getType(),
                        MaterialsTypeEnum.BASIC_MATERIALS_TYPE_VIDEO.getType(),
                        MaterialsTypeEnum.BASIC_MATERIALS_TYPE_VOICE.getType())
                .contains(basicMaterialsDto.getResourceType())) {
            if (StringUtil.isNull(file)) {
                return BaseResult.error("请选择文件");
            }
            try {
                WxPubMaterialTypeEnum wxPubMaterialTypeEnum = null;
                if (MaterialsTypeEnum.BASIC_MATERIALS_TYPE_IMAGE.getType()
                        .equals(basicMaterialsDto.getResourceType())) {
                    wxPubMaterialTypeEnum = WxPubMaterialTypeEnum.MATERIAL_TYPE_IMAGE;
                }
                if (MaterialsTypeEnum.BASIC_MATERIALS_TYPE_VIDEO.getType()
                        .equals(basicMaterialsDto.getResourceType())) {
                    wxPubMaterialTypeEnum = WxPubMaterialTypeEnum.MATERIAL_TYPE_VIDEO;
                }
                if (MaterialsTypeEnum.BASIC_MATERIALS_TYPE_VOICE.getType()
                        .equals(basicMaterialsDto.getResourceType())) {
                    wxPubMaterialTypeEnum = WxPubMaterialTypeEnum.MATERIAL_TYPE_VOICE;
                }
                if (ObjectUtil.isEmpty(wxPubMaterialTypeEnum)) {
                    return BaseResult.error("无效的素材类型");
                }
                wxPubServiceConfig();
                BaseResult baseResult = wxPubService.addMaterial(file.getInputStream(), file.getOriginalFilename(),
                        basicMaterialsDto.getTitle(), basicMaterialsDto.getContent(), wxPubMaterialTypeEnum);
                if (!baseResult.isSuccess()) {
                    return BaseResult.error("调用微信素材接口错误：" + baseResult.getData());
                }
                JSONObject json = (JSONObject) baseResult.getData();
                thirdWechatArticle.setMediaId(json.getString(KEY_MEDIA_ID));
                if (json.containsKey(KEY_URL)) {
                    thirdWechatArticle.setAttachment(json.getString(KEY_URL));
                }
                if (MaterialsTypeEnum.BASIC_MATERIALS_TYPE_IMAGE.getType().equals(basicMaterialsDto.getResourceType())) {
                    baseResult = fileResourcesService.uploadFile(file, basicMaterialsDto.getCatalogId(), cacheUserVO);
                    PrintUtil.console(baseResult);
                    if (baseResult.isSuccess()) {
                        UploadVo uploadVo = (UploadVo) baseResult.getData();
                        thirdWechatArticle.setPhoto(uploadVo.getUuid());
                    }
                }
            } catch (Exception e) {
                return BaseResult.error("调用微信素材接口发生异常：" + e.getLocalizedMessage());
            }
        }
        return super.insertSelective(thirdWechatArticle);
    }

    @Override
    public BaseResult selectDetailsByPrimaryKey(Object id) {
        ThirdWechatArticleExample wechatArticleExample = new ThirdWechatArticleExample();
        wechatArticleExample.createCriteria().andIdEqualTo(StringUtil.getString(id));
        List<ThirdWechatArticle> wechatArticleList = thirdWechatArticleMapper
                .selectByExampleWithBLOBs(wechatArticleExample);
        if (wechatArticleList.isEmpty()) {
            return BaseResult.ok();
        }
        return BaseResult.ok(wechatArticleList.get(0));
    }

    @Override
    public BaseResult changeStatus(List<String> ids, ThirdContentStatusEnum thirdContentStatusEnum) {
        ThirdWechatArticleExample contentArticleExample = new ThirdWechatArticleExample();
        contentArticleExample.createCriteria().andIdIn(ids);
        ThirdWechatArticle contentArticle = new ThirdWechatArticle();
        contentArticle.setStatus(thirdContentStatusEnum.getStatus());
        if (ThirdContentStatusEnum.CONTENT_STATUS_PUBLISHED.getStatus().equals(thirdContentStatusEnum.getStatus())) {
            contentArticle.setPublishDate(System.currentTimeMillis());
        }
        thirdWechatArticleMapper.updateByExampleSelective(contentArticle, contentArticleExample);
        return BaseResult.ok();
    }

    @Override
    public BaseResult moveRecycleBin(List<String> ids) {
        ThirdWechatArticleExample contentArticleExample = new ThirdWechatArticleExample();
        contentArticleExample.createCriteria().andIdIn(ids);
        ThirdWechatArticle contentArticle = new ThirdWechatArticle();
        contentArticle.setIsDeleted(Byte.valueOf("1"));
        thirdWechatArticleMapper.updateByExampleSelective(contentArticle, contentArticleExample);
        return BaseResult.ok();
    }

    @Override
    public BaseResult recovery(List<String> ids) {
        ThirdWechatArticleExample contentArticleExample = new ThirdWechatArticleExample();
        contentArticleExample.createCriteria().andIdIn(ids);
        ThirdWechatArticle contentArticle = new ThirdWechatArticle();
        contentArticle.setIsDeleted(Byte.valueOf("0"));
        thirdWechatArticleMapper.updateByExampleSelective(contentArticle, contentArticleExample);
        return BaseResult.ok();
    }

    @Override
    public BaseResult setAllowComment(String id, Boolean allowComment) {
        ThirdWechatArticle contentArticle = selectByPrimaryKey(id);
        if (ObjectUtil.isEmpty(contentArticle)) {
            return BaseResult.error("无效的内容");
        }
        contentArticle.setLeavingMessage(Boolean.TRUE.equals(allowComment) ? Byte.valueOf("1") : Byte.valueOf("0"));
        thirdWechatArticleMapper.updateByPrimaryKeySelective(contentArticle);
        return BaseResult.ok();
    }

    @Override
    public BaseResult view(HttpServletRequest request, String id, CacheUserVO cacheUserVO) {
        BaseResult baseResult = selectDetailsByPrimaryKey(id);
        /**
         * 后期此地方要加浏览数+1
         */
        return baseResult;
    }

    @Override
    public BaseResult findPreAndNext(String id, String categoryId,Boolean isAll) {
        Map<String, ThirdWechatArticle> map = new HashMap<>(7);
        map.put("next", thirdWechatArticleMapper.findNext(id, categoryId, isAll));
        map.put("pre", thirdWechatArticleMapper.findPrev(id, categoryId, isAll));
        return BaseResult.ok(map);
    }

}
